package cn.accjiyun.ca.common.utils;

import cn.accjiyun.ca.common.constants.CommonConstants;
import nl.bitwalker.useragentutils.Browser;
import nl.bitwalker.useragentutils.OperatingSystem;
import nl.bitwalker.useragentutils.UserAgent;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by jiyun on 2017/1/26.
 */
public class WebUtils {
    public static String MYDOMAIN;

    static {
        MYDOMAIN = CommonConstants.MYDOMAIN;
    }

    public WebUtils() {
    }

    public static void setCookie(HttpServletResponse response, String key, String value, int days) {
        setCookie(response, key, value, days, MYDOMAIN);
    }

    public static void setCookie(HttpServletResponse response, String key, String value, int days, String domain) {
        if (key != null && value != null) {
            Cookie cookie = new Cookie(key, value);
            cookie.setMaxAge(days * 24 * 60 * 60);
            cookie.setPath("/");
            if (StringUtils.isNotEmpty(domain)) {
                cookie.setDomain(domain);
            }

            response.addCookie(cookie);
        }

    }

    public static String getCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        String resValue = "";
        if (cookies != null && cookies.length > 0) {
            for (int i = 0; i < cookies.length; ++i) {
                if (key.equalsIgnoreCase(cookies[i].getName()) && StringUtils.isNotEmpty(cookies[i].getValue())) {
                    resValue = cookies[i].getValue();
                }
            }
        }

        return resValue;
    }

    public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String name) {
        deleteCookieDomain(request, response, name, MYDOMAIN);
    }

    public static void deleteCookieDomain(HttpServletRequest request, HttpServletResponse response, String name, String domain) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (int i = 0; i < cookies.length; ++i) {
                if (name.equalsIgnoreCase(cookies[i].getName())) {
                    Cookie ck = new Cookie(cookies[i].getName(), (String) null);
                    ck.setPath("/");
                    if (StringUtils.isNotEmpty(domain)) {
                        ck.setDomain(domain);
                    }

                    ck.setMaxAge(0);
                    response.addCookie(ck);
                    return;
                }
            }
        }

    }

    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }

        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1")) {
                InetAddress inet = null;

                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException var4) {
                    var4.printStackTrace();
                }

                ipAddress = inet.getHostAddress();
            }
        }

        if (ipAddress != null && ipAddress.length() > 15 && ipAddress.indexOf(",") > 0) {
            ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
        }

        return ipAddress;
    }

    public static String getServletRequestUrlParms(HttpServletRequest request) {
        StringBuffer sbUrlParms = request.getRequestURL();
        sbUrlParms.append("?");
        Enumeration parNames = request.getParameterNames();

        while (parNames.hasMoreElements()) {
            String parName = ((String) parNames.nextElement()).toString();

            try {
                sbUrlParms.append(parName).append("=").append(URLEncoder.encode(request.getParameter(parName), "UTF-8")).append("&");
            } catch (UnsupportedEncodingException var5) {
                return "";
            }
        }

        return sbUrlParms.toString();
    }

    public static String getServletRequestUriParms(HttpServletRequest request) {
        StringBuffer sbUrlParms = new StringBuffer(request.getRequestURI());
        sbUrlParms.append("?");
        Enumeration parNames = request.getParameterNames();

        while (parNames.hasMoreElements()) {
            String parName = ((String) parNames.nextElement()).toString();

            try {
                sbUrlParms.append(parName).append("=").append(URLEncoder.encode(request.getParameter(parName), "UTF-8")).append("&");
            } catch (UnsupportedEncodingException var5) {
                return "";
            }
        }

        return sbUrlParms.toString();
    }

    public static boolean checkLoginName(String value) {
        return value.matches(CommonConstants.loginRegex);
    }

    public static boolean checkMobile(String value) {
        return value.matches(CommonConstants.telRegex);
    }

    public static boolean checkEmail(String value, int length) {
        if (length == 0) {
            length = 40;
        }

        return value.matches(CommonConstants.emailRegex) && value.length() <= length;
    }

    public static boolean isPasswordAvailable(String password) {
        String partten = "^[_0-9a-zA-Z]{6,}$";
        boolean flag = password.matches(partten) && password.length() >= 6 && password.length() <= 16;
        return flag;
    }

    public static boolean isNumeric(String...ids) {
        Pattern pattern = Pattern.compile("[0-9]*");
        for (String s : ids) {
            Matcher isNum = pattern.matcher(s);
            if (!isNum.matches()) {
                return false;
            }
        }
        return true;
    }

    public static String timestampToString(Timestamp timestamp) {
        if (timestamp == null) return null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:MM");//定义格式，不显示毫秒
        return df.format(timestamp);
    }

    public static Timestamp stringToTimestamp(String dateString) {
        if (dateString == null || dateString.equals("")) return null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//定义格式，不显示毫秒
        if (dateString.length() > 10 ) {
            df = new SimpleDateFormat("yyyy-MM-dd HH:MM");
        }
        Date date = null;
        try {
            date = df.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
        return new Timestamp(date.getTime());
    }

    public static Date stringToData(String dateString) {
        if (dateString == null || dateString.equals("")) return null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//定义格式，不显示毫秒
        if (dateString.length() > 10 ) {
            df = new SimpleDateFormat("yyyy-MM-dd HH:MM");
        }
        Date date = null;
        try {
            date = df.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
        return date;
    }

    public static boolean isValidateRealString(String...ids) {
        for (String s : ids) {
            if (s == null || s.equals("")) {
                return false;
            }
        }
        return true;
    }

    //从html中提取纯文本
    public static String html2Text(String inputString) {
        String htmlStr = inputString; // 含html标签的字符串
        String textStr = "";
        Pattern p_script;
        Matcher m_script;
        Pattern p_style;
        Matcher m_style;
        Pattern p_html;
        Matcher m_html;
        try {
            String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
            String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
            String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
            p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
            m_script = p_script.matcher(htmlStr);
            htmlStr = m_script.replaceAll(""); // 过滤script标签
            p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
            m_style = p_style.matcher(htmlStr);
            htmlStr = m_style.replaceAll(""); // 过滤style标签
            p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
            m_html = p_html.matcher(htmlStr);
            htmlStr = m_html.replaceAll(""); // 过滤html标签
            textStr = htmlStr;
        } catch (Exception e) {System.err.println("Html2Text: " + e.getMessage()); }
        //剔除空格行
        textStr=textStr.replaceAll("[ ]+", " ");
        textStr=textStr.replaceAll("(?m)^\\s*$(\\n|\\r\\n)", "");
        return textStr;// 返回文本字符串
    }

    public static boolean isAjaxRequest(HttpServletRequest request) {
        String her = request.getHeader("x-requested-with");
        return StringUtils.isNotEmpty(her);
    }

    public static boolean isNotAjaxRequest(HttpServletRequest request) {
        return !isAjaxRequest(request);
    }

    public static String getUserAgent(HttpServletRequest request) {
        String uabrow = request.getHeader("User-Agent");
        UserAgent userAgent = UserAgent.parseUserAgentString(uabrow);
        Browser browser = userAgent.getBrowser();
        OperatingSystem os = userAgent.getOperatingSystem();
        return browser.getName().toLowerCase() + ";" + os.getName().toLowerCase();
    }

    public static String replaceTagHTML(String src) {
        String regex = "\\<(.+?)\\>";
        return StringUtils.isNotEmpty(src) ? src.replaceAll(regex, "") : "";
    }
}
